import React from 'react';
import { Upload, message } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import { analyzeLight } from '../utils/lightAnalysis';

const { Dragger } = Upload;

const ImageUploader = ({ onAnalysisComplete }) => {
  const props = {
    name: 'image',
    multiple: false,
    accept: '.jpg,.jpeg,.png',
    showUploadList: true,
    customRequest: async ({ file, onSuccess, onError, onProgress }) => {
      try {
        onProgress({ percent: 50 });
        const result = await analyzeLight(file);
        onProgress({ percent: 100 });
        onSuccess(result);
      } catch (error) {
        onError(error);
      }
    },
    onChange(info) {
      const { status } = info.file;
      if (status === 'uploading') {
        message.loading({ 
          content: `${info.file.name} 正在分析中...`,
          key: 'upload'
        });
      }
      if (status === 'done') {
        message.success({ 
          content: `${info.file.name} 分析完成`,
          key: 'upload'
        });
        if (info.file.response) {
          onAnalysisComplete?.(info.file.response);
        }
      } else if (status === 'error') {
        message.error({ 
          content: `分析失败: ${info.file.error?.message || '请重试'}`,
          key: 'upload'
        });
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('仅支持 JPG/PNG 格式的图片');
      }
      return isJpgOrPng;
    },
  };

  return (
    <Dragger {...props}>
      <p className="ant-upload-drag-icon">
        <InboxOutlined />
      </p>
      <p className="ant-upload-text">点击或拖拽图片到此处上传</p>
      <p className="ant-upload-hint">仅支持 JPG/PNG 格式的图片</p>
    </Dragger>
  );
};

export default ImageUploader;